<template>
  <div class="createPay">
    <div>
      <jc-button
        :btn-arr="['reload', 'copy', 'voucher', 'save', 'sub', 'remove', 'pass', 'list']"
        :disab-arr="[isDisabled && 'save', 'close', 'cancel', 'copy', 'com1', 'com2', 'using', 'freeze']"
        :list="'/transferList'"
        @refresh="transferDetails"
        @save="newlyAdjustment"
        @submit="newlyAdjustment(1)"
        @noSubmit="submit(2)"
        @audit="audit(1)"
        @noAudit="audit(2)"
        @del="remove"
        @voucher="voucher"
        @copyDa="copyPayment"
        @voucherLok="LooktialsTask"
      />
    </div>
    <el-tabs v-model="activeName" @tab-click="handleOther">
      <el-tab-pane :label="$t('market.info')" name="first">
        <el-form :model="subDetails" label-width="100px" size="mini">
          <el-form-item :label="$t('market.state')">
            <el-tag :type="subDetails.stateColor">{{ subDetails.fdocumentstatus }}</el-tag>
          </el-form-item>
          <el-form-item :label="$t('market.billType')">
            <el-input v-model="subDetails.fbilltypname" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.billNo')">
            <el-input v-model="subDetails.fbillno" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.orderDate')">
            <el-date-picker
              v-model.trim="subDetails.fdate"
              type="date"
              value-format="yyyy-MM-dd"
              :disabled="isDisabled"
            />
          </el-form-item>
          <!--          <el-form-item label="收款组织">-->
          <!--            <el-input v-model.trim="subDetails.orgcolname" disabled />-->
          <!--          </el-form-item>-->
          <el-form-item :label="$t('market.localCurr')">
            <el-input v-model.trim="subDetails.fcurrencyname" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.exchangeType')">
            <el-input v-model.trim="subDetails.fexchangetypename" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.note')">
            <el-input v-model.trim="subDetails.fremark" :disabled="isDisabled" />
          </el-form-item>
        </el-form>
        <div class="table-content">
          <div style="margin-bottom: 5px;">
            <el-button size="mini" @click="newHang">{{ $t('btn.newHang') }}<!--新增行--></el-button>
            <el-button size="mini" @click="delHang">{{ $t('btn.delHang') }}<!--删除行--></el-button>
            <el-button size="mini" @click="batchFill">{{ $t('btn.batchFill') }}<!--批量填充--></el-button>
          </div>
          <jc-table
            :table-data="tableData"
            :table-header="tableHeader"
            :table-height="tableHeight"
            serial
            @rowClick="rowClick"
            @cellClick="cellClick"
          >
            <el-table-column :label="$t('market.shiftToBank')" align="center">
              <template slot-scope="scope">
                <el-select v-model.trim="scope.row.freceiverbanknameid" filterable :disabled="isDisabled">
                  <el-option
                    v-for="option in account1"
                    :key="option.fid"
                    :label="option.fname"
                    :value="option.fid"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.shiftToAccount')" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.freceiverbankaccount" :disabled="isDisabled">
                  <i
                    slot="suffix"
                    class="el-input__icon el-icon-search"
                    @click="bankShow(scope.$index, 1)"
                  />
                </el-input>
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.rollOutBank')" align="center">
              <template slot-scope="scope">
                <el-select v-model.trim="scope.row.ftransferbanknameid" filterable :disabled="isDisabled">
                  <el-option
                    v-for="option in account1"
                    :key="option.fid"
                    :label="option.fname"
                    :value="option.fid"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.rollOutAccount')" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.ftransferbankaccount" :disabled="isDisabled">
                  <i
                    slot="suffix"
                    class="el-input__icon el-icon-search"
                    @click="bankShow(scope.$index, 2)"
                  />
                </el-input>
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.shiftToCurr')" align="center" width="120">
              <template slot-scope="scope">
                <el-input v-model="scope.row.freecivercurrencyname" :disabled="isDisabled">
                  <i
                    slot="suffix"
                    class="el-input__icon el-icon-search"
                    @click="currShow(scope.$index, 1)"
                  />
                </el-input>
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.shiftToMoney')" align="center" width="80">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.freceiveramount"
                  :min="0"
                  size="mini"
                  :disabled="isDisabled"
                />
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.rollOutMoney')" align="center" width="80">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.ftransferamount"
                  :min="0"
                  size="mini"
                  :disabled="isDisabled"
                />
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.shiftToNum')" align="center" width="120">
              <template slot-scope="scope">
                <el-input v-model.number="scope.row.freceivernum" size="mini" :disabled="isDisabled" />
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.rollOutNum')" align="center" width="120">
              <template slot-scope="scope">
                <el-input v-model.number="scope.row.ftransfernum" size="mini" :disabled="isDisabled" />
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.rollOutCurr')" align="center" width="120">
              <template slot-scope="scope">
                <el-input v-model="scope.row.ftransfercurrencyname" :disabled="isDisabled">
                  <i
                    slot="suffix"
                    class="el-input__icon el-icon-search"
                    @click="currShow(scope.$index, 2)"
                  />
                </el-input>
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.digest')" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.fabstract" size="mini" :disabled="isDisabled" />
              </template>
            </el-table-column>
            <el-table-column v-if="subDetails.fbilltypeid === 1345" :label="$t('market.chargeamount')" align="center" width="80px">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.fservicecharge" :disabled="isDisabled" size="mini" @change="handelQty(scope.$index)" />
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.shiftToRate')" align="center" width="80">
              <template slot-scope="scope">
                <el-input-number
                  v-model.number="scope.row.freciiveexchangerate"
                  :min="0"
                  size="mini"
                  :disabled="isDisabled"
                />
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.rollOutRate')" align="center" width="80">
              <template slot-scope="scope">
                <el-input-number
                  v-model.number="scope.row.ftransferexchangerate"
                  :min="0"
                  size="mini"
                  :disabled="isDisabled"
                />
              </template>
            </el-table-column>
          </jc-table>
        </div>
      </el-tab-pane>
      <el-tab-pane :label="$t('market.other')" name="log">
        <jc-marker
          ref="log"
          :fnumber="subDetails.fbillno"
          other-height="65vh"
          :other-url-object="otherUrlObject"
        />
      </el-tab-pane>
    </el-tabs>
    <!--币别-->
    <currency v-if="openCurrency" @currency="currencySelectRow" />
    <!--银行账号-->
    <bank v-if="bankVisiblit" :search="bankName" @client="bankData" />
  </div>
</template>

<script>
import { queryRate, queryViewItem } from '@/api/marketManage/marketOrder'
import autocomplete from '@/views/market/marketManage/createMarkerOrder/components/autocomplete'
import bility from '@/mixin/Operability'
import {
  updateBankTransfer,
  queryBankTransferDetails,
  submitBankTransferBill,
  notsubmitBankTransferBill, reviewBankTransfers,
  notreviewBankTransfers, delBankTransfers, createVoucherByBankTransfer
} from '@/api/financial/teller'
import { notoMxBmina, toMxBmina } from '@/components/ToMxamineState'
import jcButton from '@/components/Button'
import jcMarker from '@/components/marker'

export default {
  name: 'TransferAdd',
  components: {
    jcButton,
    jcMarker,
    bank: () => import('@/views/financial/cashier/payment/component/bank'),
    currency: () => import('@/views/market/marketManage/createMarkerOrder/components/currency')
  },
  mixins: [autocomplete, bility],
  data() {
    return {
      account1: [], // 银行
      isDisabled: false,
      bankVisiblit: false, // 银行账号
      openCurrency: false, // 币别、价目表、价格类型
      subDetails: {
        fdocumentstatus: 'A',
        fbilltypeid: 1345,
        fdate: new Date(),
        orgcolid: 1,
        fremark: ''
      },
      bankName: '',
      otherUrlObject: {},
      activeName: 'first',
      billtypes: [], // 单据类型
      indexSelf: 0,
      // 表头
      tableData: [], // 银行转账单数据
      tableHeight: '70vh',
      tableHeader: []
    }
  },
  created() {
    this.getForm()
    if (this.$route.params.id) {
      this.transferDetails()
    }
    this.tableHeight = window.innerWidth > 1440 ? 'calc(100vh - 300px)' : '73vh'
  },
  methods: {
    transferDetails() {
      const fid = this.$route.params.id
      queryBankTransferDetails({ fid }).then(res => {
        if (res.code === 0) {
          this.otherUrlObject = res.data
          this.subDetails = toMxBmina(res.data)
          this.tableData = res.data.details
          this.tableData.map(item => {
            item.ftransferamount1 = item.ftransferamount
          })
          this.isDisabled = this.subDetails.fdocumentstatus === this.$t('market.state2') || this.subDetails.fdocumentstatus === this.$t('market.state1')
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 保存
    newlyAdjustment(ev) {
      const DATA = {
        ...notoMxBmina(this.subDetails),
        details: this.tableData
      }
      updateBankTransfer(DATA).then(res => {
        if (res.code === 0) {
          ev === 1 ? this.submit(1) : this.transferDetails()
          this.$message({ showClose: true, message: res.message, type: 'success' })
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 查询汇率
    async querySalerRate(ev) {
      const DATA = {
        tocurrId: this.subDetails.fcurrencyid, // 本位币
        fromcurrId: ev, // 结算币别
        queryDate: this.subDetails.fdate
      }
      const { data: RES, code, message } = await queryRate(DATA)
      if (code === 0) {
        const item = this.tableData[this.indexSelf]
        if (this.outIn === 1) { // 转入
          item.freciiveexchangerate = RES.exchangeRate
        } else if (this.outIn === 2) { // 转出
          item.ftransferexchangerate = RES.exchangeRate
        }
      } else {
        this.$confirm(message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
      }
    },
    // 开户银行数据
    async getForm() {
      await queryViewItem({ viewName: 'SX_FIN_BANK' }).then(res => {
        this.account1 = res.data.list
      })
    },
    // 监听数量
    handelQty(index) {
      const item = this.tableData[index]
      item.ftransferamount = item.ftransferamount1 + item.fservicecharge
    },
    // 银行弹窗
    bankShow(index, ev) {
      this.outIn = ev
      const fids = ev === 1 ? this.tableData[index].freceiverbanknameid : this.tableData[index].ftransferbanknameid
      this.account1.forEach(res => {
        if (res.fid === fids) {
          this.bankName = res.fname
        }
      })
      this.indexSelf = index
      this.bankVisiblit = true
    },
    bankData(ev) {
      const item = this.tableData[this.indexSelf]
      if (ev.fbankaccountId && this.outIn === 1) { // 转入
        item.freceiverbankaccountid = ev.fbankaccountId
        item.freceiverbankaccount = ev.faccount
      } else if (ev.fbankaccountId && this.outIn === 2) { // 转出
        item.ftransferbankaccountid = ev.fbankaccountId
        item.ftransferbankaccount = ev.faccount
      }
      this.bankVisiblit = false
    },
    currShow(index, ev) {
      this.outIn = ev
      this.indexSelf = index
      this.openCurrency = true
    },
    // 币别选中
    currencySelectRow(ev) {
      const item = this.tableData[this.indexSelf]
      if (ev.fsettleCurrId && this.outIn === 1) { // 转入
        item.freecivercurrencyid = ev.fsettleCurrId
        item.freecivercurrencyname = ev.fsettleCurrIdName
        this.querySalerRate(ev.fsettleCurrId)
      } else if (ev.fsettleCurrId && this.outIn === 2) { // 转出
        item.ftransfercurrencyid = ev.fsettleCurrId
        item.ftransfercurrencyname = ev.fsettleCurrIdName
        this.querySalerRate(ev.fsettleCurrId)
      }
      this.openCurrency = false
    },
    // 单击行
    rowClick(row) {
      this.indexSelf = row.index
    },
    // 新增行
    newHang() {
      const { fcurrencyname, fcurrencyid } = this.subDetails
      this.tableData.push({
        freceiverbankaccount: '', ftransferbankaccount: '',
        freceiverbanknameid: '', freceiverbankaccountid: '',
        ftransferbanknameid: '', ftransferbankaccountid: '',
        freceiveramount: 0, ftransferamount: 0,
        freceivernum: '', ftransfernum: '',
        fservicecharge: 0, fabstract: '',
        freecivercurrencyid: fcurrencyid, ftransfercurrencyid: fcurrencyid,
        freciiveexchangerate: 1, ftransferexchangerate: 1,
        freecivercurrencyname: fcurrencyname, ftransfercurrencyname: fcurrencyname
      })
    },
    // 公共函数
    toExamineFun(api) {
      const DATA = { Numbers: [this.subDetails.fbillno] }
      api(DATA).then(res => {
        if (res.code !== 0) {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
          return
        }
        this.transferDetails()
        this.selectVal = []
        this.innerHTM = ''
        res.data.forEach(res => {
          this.innerHTM += '<div>' + res + '</div>'
        })
        this.$notify.warning({
          title: '提示',
          message: this.innerHTM,
          duration: 3000, offset: 50,
          dangerouslyUseHTMLString: true
        })
      })
    },
    // 提交
    submit(ev) {
      const api = ev === 1 ? submitBankTransferBill : notsubmitBankTransferBill
      this.toExamineFun(api)
    },
    // 审核
    audit(ev) {
      const api = ev === 1 ? reviewBankTransfers : notreviewBankTransfers
      this.toExamineFun(api)
    },
    // 删除
    remove() {
      this.$confirm('确定要删除该订单么？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const api = delBankTransfers
        const DATA = { Numbers: [this.subDetails.fbillno] }
        api(DATA).then(res => {
          if (res.code !== 0) {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
            return
          }
          this.innerHTM = ''
          res.data.forEach(res => {
            this.innerHTM += '<div>' + res + '</div>'
          })
          this.$notify.warning({
            title: '提示',
            message: this.innerHTM,
            duration: 3000, offset: 50,
            dangerouslyUseHTMLString: true
          })
          // 关闭当前页面
          this.$store.dispatch('tagsView/guanbi', this.$route)
          this.$router.push({ path: '/transferList' })
        })
      })
    },
    // 新增凭证
    voucher() {
      const DATA = {
        fids: [this.subDetails.fid]
      }
      createVoucherByBankTransfer(DATA).then(res => {
        if (res.code === 0) {
          this.$router.push({ path: `/certificateDetail/${res.data.voucherId}` })
          this.$message({ showClose: true, message: res.message, type: 'success' })
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 查看凭证
    LooktialsTask() {
      const id = this.subDetails.voucherid
      if (id) {
        this.$router.push({ path: `/certificateDetail/${id}` })
      } else {
        this.$confirm('该单据未能查询到对应的业务凭证！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
      }
    },
    // 复制
    copyPayment() {
      this.$router.push({
        path: '/transferAdd',
        query: {
          id: this.subDetails.fid
        }
      })
    },
    // 删除行
    delHang() {
      this.tableData.splice(this.indexSelf, 1)
    },
    handleOther(tab) {
      if (tab.name === 'log') {
        this.$refs.log.otherlog()
      }
    },
    // 点击单元格
    cellClick(row, column, cell, event) {
      this.property = column.property
      this.subscript = row.index
    },
    // 批量填充
    batchFill() {
      const item = this.tableData[this.subscript][this.property]
      this.tableData.map((res, index) => {
        if (index >= this.subscript) {
          res[this.property] = item
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.tabPosit {
  padding: 5px;
  box-shadow: 0 0 2px #aaa;
  position: absolute;
  top: 3.5vh;
  left: 0;
  background-color: rgba(255, 255, 255, 1);
  z-index: 99999!important;
}
.tabPosit1 {
  padding: 5px;
  box-shadow: 0 0 2px #aaa;
  position: absolute;
  top: -25.69vh;
  left:0;
  background-color: rgba(255, 255, 255, 1);
  z-index: 9999;
}
.createPay {
  @include listBom;
  .header{
    margin-top: 10px;
    .header-name{
      span {
        width: 100px;
        margin-right: 10px;
        text-align: right;
      }
    }
  }
  .el-table{
    &::v-deep .el-input-number .el-input__inner{
      padding: 0;
      width: 75px;
    }
    &::v-deep .el-input-number .el-input{
      width: 75px;
    }
    &::v-deep .el-input-number--mini{
      width: 75px
    }
    &::v-deep .el-input-number__increase{
      display: none;
    }
    &::v-deep .el-input-number__decrease{
      display: none;
    }
    &::v-deep .el-table__footer-wrapper tbody td{
      background: #fdf6ec!important;
    }
  }
  .el-input::v-deep .el-input__inner {
    height: 30px;
    line-height: 30px;
  }
  .el-form {
    display: flex;
    flex-wrap: wrap;

    .el-form-item {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      height: 35px;
      width: 268px;
      margin-bottom: 2px;

      .btnType {
        margin-right: 20px;
      }

      .el-date-editor.el-input {
        width: 100% !important;
      }

      .el-select {
        width: 100%;
      }
    }
  }
}
</style>
